package com.lu.dao.impl;

import com.lu.dao.BaseDao;
import com.lu.dao.TopicDao;
import com.lu.entity.Topic;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TopicDaoImpl extends BaseDao implements TopicDao {

    @Override
    public List<Topic> getAllTopic() {
        List<Topic> list = new ArrayList<>();
        Connection con = null;
        PreparedStatement pstmt = null;
        String sql = "select * from TOPIC";
        ResultSet rs = null;
        try {
            con = getCon();
            pstmt = con.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                int tid = rs.getInt("tid");
                String tname = rs.getString("tname");
                Topic topic = new Topic(tid, tname);
                list.add(topic);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeAll(con, pstmt, rs);
        }
        return list;
    }

    @Override
    public Topic getOneTopic(String tname) {
        Topic topic = null;
        Connection con = null;
        PreparedStatement pstmt = null;
        String sql = "select * from TOPIC where tname=?";
        ResultSet rs = null;
        try {
            con = getCon();
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, tname);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                int tid = rs.getInt("tid");
                topic = new Topic(tid, tname);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeAll(con, pstmt, rs);
        }
        return topic;
    }

    @Override
    public int deleteOneTopic(int tid) {
        String sql = "DELETE FROM TOPIC WHERE tid = ?";
        Object[] params = {tid};
        return executeUpdate(sql, params);
    }

    @Override
    public int insertOneTopic(Topic topic) {
        String sql = "insert into TOPIC(tname) values(?)";
        Object[] params = {topic.getTname()};
        return executeUpdate(sql, params);
    }
}
